package com.qdlc.p2p.dal.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.UserStatisticsDao;
import com.qdlc.p2p.dal.dto.UserStatistics;

@Repository
public class UserStatisticsDaoImpl extends BaseDaoImpl<UserStatistics> implements UserStatisticsDao {

    public void updateStatisticsCount(long userId, boolean isTender) {

        // 是否存在
        QueryParam arg = QueryParam.getInstance();
        arg.addParam("user", userId);
        List<UserStatistics> list = findByCriteria(arg);
        boolean hasStatistics = list != null && list.size() > 0;

        StringBuffer sql = new StringBuffer();
        if (hasStatistics == false) {
            sql.append("insert into ");
            sql.append(Global.DB_PREFIX);
            sql.append("user_statistics(user_id,invest_count,borrow_count)");
            sql.append(" values (");
            // 投资人
            if (isTender == true) {
                sql.append(":userId,1,0");
                // 借款人
            } else {
                sql.append(":userId,0,1");
            }
            sql.append(")");
            Query query = em.createNativeQuery(sql.toString());
            query.setParameter("userId", userId);
            query.executeUpdate();
        } else {
            UserStatistics userStatistics = list.get(0);
            long id = userStatistics.getId();
            sql.setLength(0);
            sql.append("Update UserStatistics Set ");
            // 投资人
            if (isTender == true) {
                sql.append("investCount = investCount + 1");
            } else {
                sql.append("borrowCount = borrowCount + 1");
            }
            sql.append(" where id = :id");
            Query query = em.createQuery(sql.toString());
            query.setParameter("id", id);
            query.executeUpdate();
        }
    }
}
